import { createRouter, createWebHashHistory } from 'vue-router';
import HomeView from '../views/HomeView.vue';
import LoginView from '../views/LoginView.vue';
import useAuth from '@/stores/auth.js';
import { staff } from '@/common/getData';
import ZongTiVue from '@/views/ZongTi.vue';

const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomeView,
      meta: { requiresAuth: true }
    }, {
      path: '/zongti',
      name: 'zongti',
      component: ZongTiVue,
      meta: { requiresAuth: true }
    }, {
      path: '/login',
      name: 'login',
      component: LoginView
    },
    // ,
    // {
    //   path: '/about',
    //   name: 'about',
    //   // route level code-splitting
    //   // this generates a separate chunk (About.[hash].js) for this route
    //   // which is lazy-loaded when the route is visited.
    //   component: () => import('../views/AboutView.vue')
    // }
  ]
})

router.beforeEach(async (to, from, next) => {
  const auth = useAuth();

  if (auth.isLoggedIn.value) {
    const callCheckToken = await staff('checkToken', { token: auth.token.value });
    console.log(callCheckToken);
    if (callCheckToken.state !== 'pass') auth.logout();
  }

  if (to.name === 'login' && auth.isLoggedIn.value) {
    next({ name: 'home' });
  } else if (to.name !== 'login' && !auth.isLoggedIn.value) {
    next({ name: 'login' });
  } else {
    next();
  }
})

export default router
